﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace CNWebBase
{
    public enum LoginResult
    {
        UserNotExist,
        IncorrectPassword,
        Success,
        SystemException
    }
    public partial class User
    {
        protected static string GenPasswordDigit(string UserName, string Password)
        {
            using (MD5 md5 = MD5.Create())
            {
                return Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(UserName + Password)));
            }
        }
        protected static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public bool CheckUserPassword(string Password)
        {
            return GenPasswordDigit(this.Name, Password) == this.PasswordDigit;
        }
        public void SetPassword(string Password)
        {
            this.PasswordDigit = GenPasswordDigit(this.Name, Password);
            Cache.UpdateUserBasic(this);
        }
        public static LoginResult Login(string UserName, string Password)
        {
            try
            {
                User user = Cache.GetUser(UserName);
                if (user == default(User))
                {
                    return LoginResult.UserNotExist;
                }
                else if (user.CheckUserPassword(Password))
                {

                    return LoginResult.Success;
                }
                else
                {
                    return LoginResult.IncorrectPassword;
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Can not check user name and password for login.", ex);
                return LoginResult.SystemException;
            }
        }

    }
}
